//
//  ARCommondModel.swift
//  AquaRaft
//
//  Created by 何启亮 on 2024/4/6.
//

import UIKit

/// 评价
@objcMembers
class ARCommentModel: NSObject, Codable {

    /// 类型
    enum type: Int, Codable {
    case text = 0
    case audio = 1
    }
    
    var id: String = ""
    
    /// 评价
    var comment: String?
    /// 类型
    var commentType: type = .text
    /// 录音地址
    var audioPath: String?
    var audioDuration: TimeInterval = 0.0
    /// 作者
    var authorId: String = ""
    var author: ARUserModel?
    
    /// 点赞数
    var likeNum: Int = 0
    /// 当前用户是否点赞
    var isLike: Bool = false
    
    enum CodingKeys: String, CodingKey {
        case comment, commentType, audioPath, authorId, likeNum, isLike, id, audioDuration
    }
    
    override init() {
        super.init()
    }
    
    // 重写方法
    required init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        
        id = try container.decode(String.self, forKey: .id)
        comment = try container.decodeIfPresent(String.self, forKey: .comment)
        commentType = try container.decode(type.self, forKey: .commentType)
        authorId = try container.decode(String.self, forKey: .authorId)
        likeNum = try container.decode(Int.self, forKey: .likeNum)
        isLike = try container.decode(Bool.self, forKey: .isLike)
        
        /// 沙盒地址
        if let path = try container.decodeIfPresent(String.self, forKey: .audioPath) {
            audioPath = ARFileHelper.documentsDirectory + path
        }
        audioDuration = try container.decode(TimeInterval.self, forKey: .audioDuration)
    }
    
    func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        try container.encodeIfPresent(id, forKey: .id)
        try container.encodeIfPresent(comment, forKey: .comment)
        try container.encodeIfPresent(commentType, forKey: .commentType)
        try container.encodeIfPresent(authorId, forKey: .authorId)
        try container.encodeIfPresent(likeNum, forKey: .likeNum)
        try container.encodeIfPresent(isLike, forKey: .isLike)
        
        if var audioPath = audioPath {
            // 替换
            audioPath = audioPath.replacingOccurrences(of: ARFileHelper.documentsDirectory, with: "")
            try container.encodeIfPresent(audioPath, forKey: .audioPath)
        }
        try container.encode(audioDuration, forKey: .audioDuration)
    }
    
    // MARK: - Check
    
    /// 返回模型是否有效
    func checkModelValid() -> Bool {
        
        if id.isEmpty || authorId.isEmpty {
            return false
        }
        
        // 内容
        switch commentType {
        case .text:
            return (comment ?? "").isEmpty == false
        case .audio:
            return (audioPath ?? "").isEmpty == false
        }
    }
    
}
